"""
兴趣相关API
"""
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from typing import List

from database import get_db
from models.models import User
from models.interest_models import InterestTag, UserInterestTag
from schemas.interest import InterestTagResponse, UserInterestRequest, UserInterestResponse
from routers.dependencies import get_current_user

router = APIRouter(prefix="/api/interests", tags=["兴趣"])


@router.get("/", response_model=List[InterestTagResponse])
async def get_all_interests(db: Session = Depends(get_db)):
    """获取所有兴趣标签"""
    interests = db.query(InterestTag).filter(InterestTag.status == 1).order_by(InterestTag.sort_order).all()
    return interests


@router.post("/user/save")
async def save_user_interests(
    request: UserInterestRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    保存用户选择的兴趣
    
    参数:
        interest_ids: 兴趣ID列表（可以为空列表，表示跳过兴趣选择）
    
    说明:
        - 如果interest_ids为空列表，将清除用户的所有兴趣
        - 如果interest_ids不为空，将替换用户的所有兴趣
    """
    try:
        user_id = current_user.id
        
        # 删除用户旧兴趣
        db.query(UserInterestTag).filter(UserInterestTag.user_id == user_id).delete()
        
        # 添加新兴趣（如果interest_ids不为空）
        if request.interest_ids:
            for interest_id in request.interest_ids:
                # 验证兴趣ID是否存在
                interest = db.query(InterestTag).filter(
                    InterestTag.id == interest_id,
                    InterestTag.status == 1
                ).first()
                
                if interest:
                    user_interest = UserInterestTag(
                        user_id=user_id,
                        interest_id=interest_id,
                        weight=1.0
                    )
                    db.add(user_interest)
        
        db.commit()
        
        message = "兴趣保存成功" if request.interest_ids else "已跳过兴趣选择"
        
        return JSONResponse({
            "success": True,
            "message": message,
            "count": len(request.interest_ids)
        })
    except Exception as e:
        db.rollback()
        return JSONResponse({
            "success": False,
            "message": f"保存失败: {str(e)}"
        }, status_code=400)


@router.get("/user/my", response_model=List[UserInterestResponse])
async def get_user_interests(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前用户的兴趣"""
    user_interests = db.query(UserInterestTag).filter(
        UserInterestTag.user_id == current_user.id
    ).all()
    
    return user_interests


@router.get("/user/recommendations")
async def get_recommendations(
    limit: int = 20,
    offset: int = 0,
    sort_by: str = "popular",  # popular: 综合热度, like: 点赞量, collect: 收藏量
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    根据用户兴趣推荐内容
    
    参数:
        limit: 返回数量限制
        offset: 偏移量
        sort_by: 排序方式
            - popular: 综合热度（点赞量+收藏量，默认）
            - like: 按点赞量排序
            - collect: 按收藏量排序
    
    返回: 与用户兴趣匹配的内容列表
    说明: 如果用户没有选择兴趣，返回热门内容（按指定排序方式）
    """
    from models.models import Content
    import json
    from sqlalchemy import desc, func, text
    
    # 1. 获取用户选择的兴趣
    user_id = current_user.id
    user_interests = db.query(UserInterestTag).filter(
        UserInterestTag.user_id == user_id
    ).all()
        
    if not user_interests:
        # 没有选择兴趣，返回热门内容（按指定排序方式）
        if sort_by == "like":
            # 按点赞量排序
            contents = db.query(Content).filter(
                Content.status == 1
            ).order_by(
                Content.like_count.desc(),
                Content.created_at.desc()
            ).limit(limit).offset(offset).all()
        elif sort_by == "collect":
            # 按收藏量排序
            contents = db.query(Content).filter(
                Content.status == 1
            ).order_by(
                Content.collect_count.desc(),
                Content.created_at.desc()
            ).limit(limit).offset(offset).all()
        else:
            # 综合热度排序（点赞量+收藏量）
            # 先查询所有数据，然后在Python中排序（避免SQL兼容性问题）
            try:
                all_contents = db.query(Content).filter(
                    Content.status == 1
                ).all()
                
                # 在Python中按综合热度排序
                contents = sorted(
                    all_contents,
                    key=lambda x: (x.like_count or 0) + (x.collect_count or 0),
                    reverse=True
                )
                
                # 应用分页
                contents = contents[offset:offset + limit]
            except Exception as e:
                # 如果排序失败，回退到按点赞量排序
                print(f"[推荐] 综合排序失败，回退到点赞量排序: {e}")
                import traceback
                traceback.print_exc()
                contents = db.query(Content).filter(
                    Content.status == 1
                ).order_by(
                    Content.like_count.desc(),
                    Content.created_at.desc()
                ).limit(limit).offset(offset).all()
    else:
        # 2. 提取兴趣名称（频道名称）
        interest_ids = [ui.interest_id for ui in user_interests]
        interest_tags = db.query(InterestTag).filter(
            InterestTag.id.in_(interest_ids)
        ).all()
        channel_names = [tag.name for tag in interest_tags]
        
        # 3. 优先显示与用户兴趣匹配的内容
        all_contents = db.query(Content).filter(Content.status == 1).all()
        
        matched_contents = []
        other_contents = []
        
        for content in all_contents:
            # 解析内容的标签
            if isinstance(content.tags, str):
                content_tags = json.loads(content.tags) if content.tags else []
            else:
                content_tags = content.tags or []
            
            # 检查内容标签是否与用户频道匹配
            if any(tag in channel_names for tag in content_tags):
                matched_contents.append(content)
            else:
                other_contents.append(content)
        
        # 对匹配内容和补充内容分别按指定方式排序
        if sort_by == "like":
            # 按点赞量排序
            matched_contents.sort(key=lambda x: x.like_count or 0, reverse=True)
            other_contents.sort(key=lambda x: x.like_count or 0, reverse=True)
        elif sort_by == "collect":
            # 按收藏量排序
            matched_contents.sort(key=lambda x: x.collect_count or 0, reverse=True)
            other_contents.sort(key=lambda x: x.collect_count or 0, reverse=True)
        else:
            # 综合热度排序（点赞量+收藏量）
            matched_contents.sort(key=lambda x: (x.like_count or 0) + (x.collect_count or 0), reverse=True)
            other_contents.sort(key=lambda x: (x.like_count or 0) + (x.collect_count or 0), reverse=True)
        
        # 组合内容：优先匹配内容，不足时补充热门内容
        if len(matched_contents) < limit:
            matched_contents.extend(other_contents[:limit - len(matched_contents)])
        
        # 最终结果（已经排序）
        contents = matched_contents[:limit]
    
    # 构建响应
    result = []
    try:
        for content in contents:
            try:
                author = db.query(User).filter(User.id == content.user_id).first()
                
                # 安全地解析JSON
                media_urls = []
                if content.media_urls:
                    if isinstance(content.media_urls, list):
                        media_urls = content.media_urls
                    elif isinstance(content.media_urls, str):
                        try:
                            media_urls = json.loads(content.media_urls)
                        except:
                            media_urls = []
                
                tags = []
                if content.tags:
                    if isinstance(content.tags, list):
                        tags = content.tags
                    elif isinstance(content.tags, str):
                        try:
                            tags = json.loads(content.tags)
                        except:
                            tags = []
                
                result.append({
                    "id": content.id,
                    "user_id": content.user_id,
                    "title": content.title or '无标题',
                    "content": content.content or '',
                    "media_urls": media_urls,
                    "tags": tags,
                    "like_count": content.like_count or 0,
                    "view_count": content.view_count or 0,
                    "collect_count": content.collect_count or 0,
                    "comment_count": content.comment_count or 0,
                    "created_at": content.created_at.isoformat() if content.created_at else None,
                    "author_nickname": author.nickname if author else '游客',
                    "author_avatar": author.avatar_url if author else None
                })
            except Exception as e:
                # 跳过有问题的内容
                import logging
                logging.error(f"处理内容 {content.id} 时出错: {e}")
                continue
        
        return JSONResponse({
            "success": True,
            "data": result,
            "count": len(result)
        })
    except Exception as e:
        import traceback
        traceback.print_exc()
        print(f"[推荐API] 构建响应失败: {e}")
        # 返回空结果而不是抛出异常
        return JSONResponse({
            "success": True,
            "data": [],
            "count": 0
        })
